import React, { useEffect, useRef } from 'react';
import Editor, { OnMount, OnChange } from '@monaco-editor/react';
import * as monaco from 'monaco-editor';
import { useEditorStore } from '../store/useEditorStore';
import { MonacoTheme } from '../types';

interface MonacoEditorProps {
  className?: string;
}

const MonacoEditor: React.FC<MonacoEditorProps> = ({ className = '' }) => {
  const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
  const {
    content,
    settings,
    validation,
    setContent,
    setCursorPosition,
    markDirty
  } = useEditorStore();

  // 获取编辑器主题
  const getEditorTheme = (): MonacoTheme => {
    if (settings.theme === 'dark') return 'vs-dark';
    if (settings.theme === 'light') return 'vs-light';
    
    // 自动模式：检测系统主题
    const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    return isDark ? 'vs-dark' : 'vs-light';
  };

  // 编辑器挂载时的回调
  const handleEditorDidMount: OnMount = (editor, monaco) => {
    editorRef.current = editor;
    
    // 配置YAML语言支持
    monaco.languages.register({ id: 'yaml' });
    
    // 设置YAML语法高亮
    monaco.languages.setMonarchTokensProvider('yaml', {
      tokenizer: {
        root: [
          // 注释
          [/#.*$/, 'comment'],
          
          // 字符串
          [/"([^"\\]|\\.)*$/, 'string.invalid'],
          [/"/, 'string', '@string_double'],
          [/'([^'\\]|\\.)*$/, 'string.invalid'],
          [/'/, 'string', '@string_single'],
          
          // 数字
          [/-?\d*\.\d+([eE][+-]?\d+)?/, 'number.float'],
          [/-?\d+/, 'number'],
          
          // 布尔值
          [/\b(true|false|yes|no|on|off)\b/, 'keyword'],
          
          // null值
          [/\b(null|~)\b/, 'keyword'],
          
          // 键
          [/^\s*[^\s:]+(?=\s*:)/, 'key'],
          [/[^\s:]+(?=\s*:)/, 'key'],
          
          // 操作符
          [/:/, 'operator'],
          [/-/, 'operator'],
          [/\|/, 'operator'],
          [/>/, 'operator'],
          
          // 分隔符
          [/[{}\[\],]/, 'delimiter'],
          
          // 空白字符
          [/\s+/, 'white']
        ],
        
        string_double: [
          [/[^\\"]+/, 'string'],
          [/\\./, 'string.escape'],
          [/"/, 'string', '@pop']
        ],
        
        string_single: [
          [/[^\\']+/, 'string'],
          [/\\./, 'string.escape'],
          [/'/, 'string', '@pop']
        ]
      }
    });
    
    // 设置编辑器配置
    monaco.languages.setLanguageConfiguration('yaml', {
      brackets: [
        ['{', '}'],
        ['[', ']']
      ],
      autoClosingPairs: [
        { open: '{', close: '}' },
        { open: '[', close: ']' },
        { open: '"', close: '"' },
        { open: "'", close: "'" }
      ],
      surroundingPairs: [
        { open: '{', close: '}' },
        { open: '[', close: ']' },
        { open: '"', close: '"' },
        { open: "'", close: "'" }
      ],
      folding: {
        offSide: true
      }
    });
    
    // 监听光标位置变化
    editor.onDidChangeCursorPosition((e) => {
      const position = editor.getModel()?.getOffsetAt(e.position) || 0;
      setCursorPosition(position);
    });
    
    // 监听内容变化
    editor.onDidChangeModelContent(() => {
      markDirty();
    });
    
    // 设置快捷键
    editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
      // 保存文件
      useEditorStore.getState().saveFile();
    });
    
    editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyF, () => {
      // 格式化代码
      editor.getAction('editor.action.formatDocument')?.run();
    });
  };

  // 内容变化时的回调
  const handleEditorChange: OnChange = (value) => {
    if (value !== undefined) {
      setContent(value);
    }
  };

  // 更新错误标记
  useEffect(() => {
    if (editorRef.current && validation.errors.length > 0) {
      const model = editorRef.current.getModel();
      if (model) {
        const markers = validation.errors.map(error => ({
          startLineNumber: error.line,
          startColumn: error.column,
          endLineNumber: error.line,
          endColumn: error.column + 10, // 简单的错误范围
          message: error.message,
          severity: monaco.MarkerSeverity.Error
        }));
        
        monaco.editor.setModelMarkers(model, 'yaml', markers);
      }
    }
  }, [validation]);

  return (
    <div className={`h-full ${className}`}>
      <Editor
        height="100%"
        language="yaml"
        theme={getEditorTheme()}
        value={content}
        onChange={handleEditorChange}
        onMount={handleEditorDidMount}
        options={{
          fontSize: settings.fontSize,
          tabSize: settings.tabSize,
          insertSpaces: true,
          wordWrap: settings.wordWrap ? 'on' : 'off',
          lineNumbers: settings.showLineNumbers ? 'on' : 'off',
          minimap: {
            enabled: settings.showMinimap
          },
          scrollBeyondLastLine: false,
          automaticLayout: true,
          formatOnPaste: true,
          formatOnType: true,
          folding: true,
          foldingStrategy: 'indentation',
          showFoldingControls: 'always',
          bracketPairColorization: {
            enabled: true
          },
          guides: {
            indentation: true,
            bracketPairs: true
          },
          suggest: {
            showKeywords: true,
            showSnippets: true
          },
          quickSuggestions: {
            other: true,
            comments: false,
            strings: false
          },
          parameterHints: {
            enabled: true
          },
          hover: {
            enabled: true
          },
          contextmenu: true,
          mouseWheelZoom: true,
          cursorBlinking: 'smooth',
          cursorSmoothCaretAnimation: 'on',
          smoothScrolling: true,
          selectOnLineNumbers: true,
          roundedSelection: false,
          readOnly: false,
          cursorStyle: 'line',
          fontFamily: 'Consolas, Monaco, "Courier New", monospace',
          fontLigatures: true,
          renderWhitespace: 'selection',
          renderControlCharacters: false,
          rulers: [80, 120],
          colorDecorators: true,
          codeLens: false,
          foldingHighlight: true,
          unfoldOnClickAfterEndOfLine: false,
          showUnused: true
        }}
        loading={
          <div className="h-full flex items-center justify-center text-gray-500">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
              <div>编辑器加载中...</div>
            </div>
          </div>
        }
      />
    </div>
  );
};

export default MonacoEditor;